package com.ruoyi.cqjd.controller;

import java.time.LocalDateTime;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.cqjd.common.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cqjd.domain.CqjdShoppingCart;
import com.ruoyi.cqjd.service.ICqjdShoppingCartService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 购物车Controller
 * 
 * @author ruoyi
 * @date 2022-06-19
 */
@RestController
@RequestMapping("/cqjd/cqjd_shopping_cart")
public class CqjdShoppingCartController extends BaseController
{
    @Autowired
    private ICqjdShoppingCartService cqjdShoppingCartService;


    /**
     * 给购物车添加菜品/套餐
     * @param shoppingCart
     * @return
     */
    @PostMapping("/front_add")
    public R<CqjdShoppingCart> frontAdd(@RequestBody CqjdShoppingCart shoppingCart, HttpSession session){
//        设置userId，确定当前菜品是哪个用户的
//        Long currentId = BaseContext.getCurrentId();
        Long userId = (Long) session.getAttribute("user");
        System.out.println(userId);
        shoppingCart.setUserId(userId);

//        查询当前菜品是否存在
//        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShoppingCart::getUserId,currentId);
//        Long dishId = shoppingCart.getDishId();
//        if (dishId!=null){
//            queryWrapper.eq(ShoppingCart::getDishId,dishId);
//        }else {
//            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
//        }
//        ShoppingCart one = shoppingCartService.getOne(queryWrapper);

        Long dishId = shoppingCart.getDishId();
        CqjdShoppingCart one = cqjdShoppingCartService.getOneByUserIdAndDishId(shoppingCart);

        if (one!=null){
//        存在数量+1
            Long number = one.getNumber();
            one.setNumber(number+1);
//            cqjdShoppingCartService.updateById(one);
            cqjdShoppingCartService.updateCqjdShoppingCart(one);
        }else {
//        不存在数量为1
            shoppingCart.setNumber(1L);
//            shoppingCart.setCreateTime(LocalDateTime.now());
            cqjdShoppingCartService.insertCqjdShoppingCart(shoppingCart);
            one=shoppingCart;
        }
        return R.ok(one);
    }

    /**
     * 给购物车减少菜品/套餐
     * @param shoppingCart
     * @return
     */
    @PostMapping("/front_sub")
    public R<CqjdShoppingCart> frontSub(@RequestBody CqjdShoppingCart shoppingCart, HttpSession session){
//        设置userId，确定当前菜品是哪个用户的
//        Long currentId = BaseContext.getCurrentId();
        Long userId = (Long) session.getAttribute("user");
        System.out.println(userId);
        shoppingCart.setUserId(userId);

//        查询当前菜品是否存在
//        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShoppingCart::getUserId,currentId);
//        Long dishId = shoppingCart.getDishId();
//        if (dishId!=null){
//            queryWrapper.eq(ShoppingCart::getDishId,dishId);
//        }else {
//            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
//        }
//        ShoppingCart one = shoppingCartService.getOne(queryWrapper);

        Long dishId = shoppingCart.getDishId();
        CqjdShoppingCart one = cqjdShoppingCartService.getOneByUserIdAndDishId(shoppingCart);

        if (one!=null){
//        存在数量-1
            Long number = one.getNumber();
            if (number>1){

            one.setNumber(number-1);
//            one.setNumber(number+1);
//            cqjdShoppingCartService.updateById(one);
            cqjdShoppingCartService.updateCqjdShoppingCart(one);
            }else if (number==1){
                cqjdShoppingCartService.deleteCqjdShoppingCartById(one.getId());
            }
        }
//        else {
////        不存在数量为1
//            shoppingCart.setNumber(1L);
////            shoppingCart.setCreateTime(LocalDateTime.now());
//            cqjdShoppingCartService.insertCqjdShoppingCart(shoppingCart);
//            one=shoppingCart;
//        }
        return R.ok(one);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/front_clean")
    public R<String> clean(HttpSession session){
//        LambdaQueryWrapper<CqjdShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
//        shoppingCartService.remove(queryWrapper);

        Long userId = (Long) session.getAttribute("user");
        cqjdShoppingCartService.removeByUserId(userId);
        return R.ok("清空购物车成功");
    }


    @GetMapping("/front_list")
    public R<List<CqjdShoppingCart>> list(HttpSession session){
//        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
//        queryWrapper.orderByDesc(ShoppingCart::getCreateTime);


//        Long userId = BaseContext.getCurrentId();
        Long userId = (Long) session.getAttribute("user");
        List<CqjdShoppingCart> list = cqjdShoppingCartService.getListByUserId(userId);
        System.out.println(list);
        return R.ok(list);
    }


    /**
     * 查询购物车列表
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_shopping_cart:list')")
    @GetMapping("/list")
    public TableDataInfo list(CqjdShoppingCart cqjdShoppingCart)
    {
        startPage();
        List<CqjdShoppingCart> list = cqjdShoppingCartService.selectCqjdShoppingCartList(cqjdShoppingCart);
        return getDataTable(list);
    }

    /**
     * 导出购物车列表
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_shopping_cart:export')")
    @Log(title = "购物车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CqjdShoppingCart cqjdShoppingCart)
    {
        List<CqjdShoppingCart> list = cqjdShoppingCartService.selectCqjdShoppingCartList(cqjdShoppingCart);
        ExcelUtil<CqjdShoppingCart> util = new ExcelUtil<CqjdShoppingCart>(CqjdShoppingCart.class);
        util.exportExcel(response, list, "购物车数据");
    }

    /**
     * 获取购物车详细信息
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_shopping_cart:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(cqjdShoppingCartService.selectCqjdShoppingCartById(id));
    }

    /**
     * 新增购物车
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_shopping_cart:add')")
    @Log(title = "购物车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CqjdShoppingCart cqjdShoppingCart)
    {
        return toAjax(cqjdShoppingCartService.insertCqjdShoppingCart(cqjdShoppingCart));
    }

    /**
     * 修改购物车
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_shopping_cart:edit')")
    @Log(title = "购物车", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CqjdShoppingCart cqjdShoppingCart)
    {
        return toAjax(cqjdShoppingCartService.updateCqjdShoppingCart(cqjdShoppingCart));
    }

    /**
     * 删除购物车
     */
//    @PreAuthorize("@ss.hasPermi('cqjd:cqjd_shopping_cart:remove')")
    @Log(title = "购物车", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(cqjdShoppingCartService.deleteCqjdShoppingCartByIds(ids));
    }
}
